package com.atguigu.day07;

import com.atguigu.utils.ClickEvent;
import com.atguigu.utils.ClickSource;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoFlatMapFunction;
import org.apache.flink.util.Collector;

// 查询流
public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> queryStream = env.socketTextStream("localhost", 9999);

        DataStreamSource<ClickEvent> clickStream = env.addSource(new ClickSource());

        clickStream
                .keyBy(r -> r.url)
                .connect(
                        // 广播之前，将并行度设置为1，保证按顺序广播数据
                        queryStream.setParallelism(1).broadcast()
                )
                .flatMap(new Query())
                .print();

        env.execute();
    }

    public static class Query implements CoFlatMapFunction<ClickEvent, String, ClickEvent> {
        private String queryString = "";
        @Override
        public void flatMap1(ClickEvent in1, Collector<ClickEvent> out) throws Exception {
            if (in1.username.equals(queryString)) out.collect(in1);
        }

        @Override
        public void flatMap2(String in2, Collector<ClickEvent> out) throws Exception {
            queryString = in2;
        }
    }
}
